import { Request, RequestHandler, Response } from "express";
import {
  IGetProjectChangeByIdReq,
  IAddProjectChangeReq,
  IGetProjectChangeByPIdReq,
  IUpdateProjectChangeReq,
  IDeleteProjectChangeReq,
  IProjectChange,
} from "../../models/project-change.model";
import * as ProjectChangeService from "../services/project-change.service";
import * as ResearchGroupService from "../services/research-group.service";
import { getCurrentDate, convertToLocalDateString } from "../utils/date";
/**
 * Get active projectChange records
 *
 * @param req Express Request
 * @param res Express Response
 */
export const getProjectChanges: RequestHandler = async (
  req: Request,
  res: Response
) => {
  try {
    const projectChanges = await ProjectChangeService.getProjectChanges();

    res.status(200).json({
      data: projectChanges,
      code: 2000,
    });
  } catch (error) {
    console.error(
      "[projectChanges.controller][getProjectChanges][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "项目变更列表获取失败！",
    });
  }
};

/**
 * Get done projectChange records
 *
 * @param req Express Request
 * @param res Express Response
 */
export const getDoneProjectChanges: RequestHandler = async (
    req: Request,
    res: Response
  ) => {
    try {
      const projectChanges = await ProjectChangeService.getDoneProjectChanges();
  
      res.status(200).json({
        data: projectChanges,
        code: 2000,
      });
    } catch (error) {
      console.error(
        "[projectChanges.controller][getProjectChanges][Error] ",
        typeof error === "object" ? JSON.stringify(error) : error
      );
      res.status(500).json({
        message: "项目变更列表获取失败！",
      });
    }
  };

  /**
 * Get in progress projectChange records
 *
 * @param req Express Request
 * @param res Express Response
 */
export const getInProgressProjectChanges: RequestHandler = async (
    req: Request,
    res: Response
  ) => {
    try {
      const projectChanges = await ProjectChangeService.getInProgressProjectChanges();
  
      res.status(200).json({
        data: projectChanges,
        code: 2000,
      });
    } catch (error) {
      console.error(
        "[projectChanges.controller][getInProgressProjectChanges][Error] ",
        typeof error === "object" ? JSON.stringify(error) : error
      );
      res.status(500).json({
        message: "项目变更列表获取失败！",
      });
    }
  };

/**
 * Get projectChange record based on id provided
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const getProjectChangeById: RequestHandler = async (
  req: IGetProjectChangeByIdReq,
  res: Response
) => {
  try {
    const projectChange = await ProjectChangeService.getProjectChangeById(
      req.params.id
    );

    res.status(200).json({
      data: projectChange,
      code: 2000,
    });
  } catch (error) {
    console.error(
      "[projectChanges.controller][getProjectChangeById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "项目变更信息获取失败！",
    });
  }
};

/**
 * Get projectChange record based on project id provided
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const getProjectChangeByPId: RequestHandler = async (
  req: IGetProjectChangeByPIdReq,
  res: Response
) => {
  try {
    const projectChanges = await ProjectChangeService.getProjectChangesByPId(
      req.params.id
    );

    res.status(200).json({
      data: projectChanges,
      code: 2000,
    });
  } catch (error) {
    console.error(
      "[projectChanges.controller][getProjectChangeById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "项目变更信息列表获取失败！",
    });
  }
};

/**
 * Get projectChange record based on participate id provided
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const getDoneProjectChangeByUser: RequestHandler = async (
    req: IGetProjectChangeByIdReq,
    res: Response
  ) => {
    try {
        let owenedProjectChanges: IProjectChange[] =[];
        const owenResearchGroups = await ResearchGroupService.getResearchGroupByOwnerId(req.params.id);
        const groupIds: number[] = [];
        if (owenResearchGroups && owenResearchGroups.length > 0) {
          owenResearchGroups.map(group => {
            groupIds.push(group.id);
          })
          if (groupIds.length > 0) {
            owenedProjectChanges = await ProjectChangeService.getDoneProjectChangesByGroups(groupIds);
          }
        }

        let participatedProjectChanges: IProjectChange[] = [];
        const allGroups = await ResearchGroupService.getResearchGroups();
        const participateGroupIds: number[] = [];
        const participatedGroups: any[]=[];
        allGroups.forEach((group) => {
            const members = group.researchGroupMembers?.length > 0
                      ? JSON.parse(group.researchGroupMembers as unknown as string)
                      : [];
            let isIn = false;
            members.forEach((item: any) => {
              if (req.params.id === (item as any).researchGroupMemberId.toString() && !groupIds.includes(group.id)) {
                isIn = true;
              }
            })
            if (isIn) {
              participatedGroups.push(group);
              participateGroupIds.push(group.id)
            }
          })  

        if (participateGroupIds && participateGroupIds.length > 0) {
            participatedProjectChanges = await ProjectChangeService.getDoneProjectChangesByGroups(participateGroupIds);
        }
  
      res.status(200).json({
        data: participatedProjectChanges.concat(owenedProjectChanges),
        code: 2000,
      });
    } catch (error) {
      console.error(
        "[projectChanges.controller][getProjectChangeById][Error] ",
        typeof error === "object" ? JSON.stringify(error) : error
      );
      res.status(500).json({
        message: "项目变更信息获取失败！",
      });
    }
  };

/**
 * Inserts a new projectChange record
 *
 * @param req Express Request
 * @param res Express Response
 */
export const addProjectChange: RequestHandler = async (
  req: IAddProjectChangeReq,
  res: Response
) => {
  try {
    req.body.projectAppliedCostItems =
      req.body.projectAppliedCostItems?.length > 0
        ? JSON.stringify(req.body.projectAppliedCostItems)
        : null;
    req.body.projectMembers =
        req.body.projectMembers?.length > 0
          ? JSON.stringify(req.body.projectMembers)
          : null;
    req.body.projectCreatedDate = req.body.projectCreatedDate
          ? convertToLocalDateString(req.body.projectCreatedDate)
          : null;
    req.body.projectStartDate = req.body.projectStartDate
          ? convertToLocalDateString(req.body.projectStartDate)
          : null;
    req.body.projectExpectedEndDate = req.body.projectExpectedEndDate
          ? convertToLocalDateString(req.body.projectExpectedEndDate)
          : null;
    req.body.projectChangeRequestDate = getCurrentDate();
    const result = await ProjectChangeService.insertProjectChange(req.body);

    res.status(200).json({
      data: result,
      code: 2000,
    });
  } catch (error) {
    console.error(
      "[projectChanges.controller][addProjectChange][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "项目变更信息保存失败！",
    });
  }
};

/**
 * Updates existing project record
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const updateProjectChangeById: RequestHandler = async (
    req: IUpdateProjectChangeReq,
    res: Response
  ) => {
    try {
        req.body.projectChangeRequestDate = getCurrentDate();
  
      const result = await ProjectChangeService.updateProjectChange({
        ...req.body,
        id: req.params.id,
      });
  
      res.status(200).json({
        data: result,
        code: 2000,
      })
    } catch (error) {
      console.error(
        "[projects.controller][updateProjectById][Error] ",
        typeof error === "object" ? JSON.stringify(error) : error
      );
      res.status(500).json({
        message: "项目变更信息更新失败！",
      });
    }
  };


/**
 * deletes a projectChange
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const deleteProjectChangeById: RequestHandler = async (
  req: IDeleteProjectChangeReq,
  res: Response
) => {
  try {
    const result = await ProjectChangeService.deleteProjectChange(req.params.id);

    res.status(200).json({
      data: result,
      code: 2000,
    });
  } catch (error) {
    console.error(
      "[projectChanges.controller][deleteProjectChangeById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "项目变更信息删除失败！",
    });
  }
};
